package cn.com.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HmacSha256Utils {
	public static byte[] hmacSHA256(String data, String secret) {
		try {
			// Create HMAC-SHA256 key from the given secret
			SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256");

			// Get an instance of Mac object implementing HMAC-SHA256
			Mac mac = Mac.getInstance("HmacSHA256");
			mac.init(secretKeySpec);

			// Calculate the HMAC value
			byte[] hmacBytes = mac.doFinal(data.getBytes());
			return hmacBytes;
			/*// Convert result into a hexadecimal string
			StringBuilder sb = new StringBuilder(hmacBytes.length * 2);
			for (byte b : hmacBytes) {
				sb.append(String.format("%02x", b));
			}
			return sb.toString();*/
		} catch (NoSuchAlgorithmException | InvalidKeyException e) {
			throw new RuntimeException("Failed to calculate HMAC-SHA256", e);
		}
	}
	
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		// 层级1
		// String url = "/Videos/QueryVideo/GetGroupsOffline?api=admin&isMobile=1&offline=0&parentId=&parentType=domain";
		// 层级2
		// String url = "/Videos/QueryVideo/GetGroupsOffline?api=admin&isMobile=1&offline=0&parentId=674cd317-a755-4b85-9d00-10e89cacf212&parentType=domain";
		// 层级3 
		// String url = "/Videos/QueryVideo/GetGroupsOffline?api=admin&isMobile=1&offline=0&parentId=a3e9cfca-8433-4b19-8534-02d875f79e3e&parentType=group";
		// String url = "/Videos/QueryVideo/GetGroupsOffline?api=admin&isMobile=1&offline=0&parentId=4598&parentType=group";
		
		
		String url = "/Videos/QueryVideo/GetLivePlayUrl?api=admin&cameraId=161544&stream=0";
		
		String encrypt = MD5Utils.encrypt("pass");
		System.out.println(encrypt);
		byte[] hmacSHA256 = hmacSHA256(url,encrypt);
		System.out.println(hmacSHA256);
		byte[] encodedBytes = Base64.getEncoder().encode(hmacSHA256);
        System.out.println(new String(encodedBytes));
        // 9rCclx9vu1QJ3qm5ebjAQMwI%2FPXzUeG8V%2BsYoU%2F85JQ%3D
        String encodedString = URLEncoder.encode(new String(encodedBytes),"UTF-8");
        System.out.println(encodedString);
        
       // System.out.println("curl 'http://61.240.141.84:7001/" + url + "&sign=" + encodedString + "'");
        System.out.println("http://61.240.141.84:7001" + url + "&sign=" + encodedString);

	}
	
}
